/**
 * This file is Copyright © 2008 Software Craftsmen Limited. All Rights Reserved.
 */
package com.softwarecraftsmen.cachecontrol.caches;

import com.softwarecraftsmen.cachecontrol.CacheItem;
import com.softwarecraftsmen.cachecontrol.Item;
import com.softwarecraftsmen.functors.UnaryFunctor;
import com.softwarecraftsmen.cachecontrol.keys.Key;
import org.jetbrains.annotations.NotNull;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

//TODO: Make sure hash() and exactlyMatches() are used!
public class ThreadSafeHashMapCache<V> extends AbstractComptrolledCache<V>
{
	private ConcurrentHashMap<Key<V>, V> internalCache;

	public ThreadSafeHashMapCache(@NotNull final Key<V> identifier)
	{
		super(identifier);
		internalCache = new ConcurrentHashMap<Key<V>, V>();
	}

	public @NotNull	Item<V> obtain(@NotNull final Key<V> key)
	{
		return new CacheItem<V>(this, key, internalCache.get(key));
	}

	@NotNull public Item<V> store(final @NotNull Key<V> key, final @NotNull V value)
	{
		internalCache.put(key, value);
		return new CacheItem<V>(this, key, value);
	}

	public void invalidate()
	{
		internalCache.clear();
	}

	public void forEach(final UnaryFunctor<CacheItem<V>> unaryFunctor)
	{
		for(Map.Entry<Key<V>, V> entry : internalCache.entrySet())
		{
			unaryFunctor.closure(new CacheItem<V>(this, entry.getKey(), entry.getValue()));
		}
	}
}
